# -*- coding: utf-8 -*-
# @Time    :2022/1/12 22:47
# @AUTHOR  :MORAN
# @Email   :moran@maqu.com
# @File    :utils.py
# @Software:PyCharm
from functools import update_wrapper

from django.contrib.auth.models import Group
from django_redis import get_redis_connection
from rest_framework.permissions import BasePermission

from config.dbs.redisConfig import LOGIN_KEY_TEMPLATE


class MyPermission(BasePermission):
    def has_permission(self, request, view):
        # 得到当前拥有token的用户
        user = request.user
        # 获取当前有权限的分组
        group = Group.objects.filter(name='老师').first()
        # 获得当前用户所属的所有分组
        groups = user.groups.all()
        return user.is_superuser or group in groups


class ActiveUserPermission(BasePermission):
    def has_permission(self, request, view):
        user = request.user
        return user.id == int(view.kwargs['pk'])


def jwt_token_redis(token, user=None, request=None):
    """
    自定义验证成功返回数据处理
    :param token:
    :param user:
    :param request:
    :return:
    """
    # 验证码校验 大小写不区分
    param = request.data
    cache = get_redis_connection(alias='verify_code')  # 获取连接对象
    redis_verify = cache.get(LOGIN_KEY_TEMPLATE % param['uuid'])

    if not redis_verify:
        return {'msg': '验证码过期'}

    if redis_verify.upper() != param['verify'].upper():
        return {'msg': '验证码错误'}

    data = {
        'token': token,
        'username': user.username,
        'id': user.id,
        'avatar': user.userdetail.avatar if hasattr(user, 'userdetail') else None
    }
    return data


def wrap_permission(*permissions, validate_permission=True):
    def decorator(func):
        def wrapper(self, request, *args, **kwargs):
            self.permission_classes = permissions
            if validate_permission:
                self.check_permissions(request)
            return func(self, request, *args, **kwargs)
        return update_wrapper(wrapper, func)
    return decorator  # 装饰器本质上是函数，形式是外层函数返回内层函数的函数体供外部调用
